<template>
  <div class="donor-list">
    <h2 class="page-title">Donor Management</h2>

    <!-- Search and Filter -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="Keyword">
          <el-input
            v-model="searchForm.keyword"
            placeholder="Search name/code"
            clearable
            @clear="handleSearch"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="Blood Type">
          <el-select v-model="searchForm.blood_type" placeholder="Select blood type" clearable style="width: 150px">
            <el-option label="A+" value="A+" />
            <el-option label="A-" value="A-" />
            <el-option label="B+" value="B+" />
            <el-option label="B-" value="B-" />
            <el-option label="AB+" value="AB+" />
            <el-option label="AB-" value="AB-" />
            <el-option label="O+" value="O+" />
            <el-option label="O-" value="O-" />
          </el-select>
        </el-form-item>
        <el-form-item label="Status">
          <el-select v-model="searchForm.is_active" placeholder="Select status" clearable style="width: 150px">
            <el-option label="Active" :value="true" />
            <el-option label="Inactive" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            Search
          </el-button>
          <el-button @click="handleReset">Reset</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- Action Bar -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>Donor List</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            Add Donor
          </el-button>
        </div>
      </template>

      <!-- Table -->
      <el-table
        v-loading="loading"
        :data="donorList"
        style="width: 100%"
      >
        <el-table-column prop="donor_id" label="ID" width="60" />
        <el-table-column prop="donor_code" label="Code" width="120" />
        <el-table-column prop="full_name" label="Full Name" width="130" />
        <el-table-column prop="blood_type" label="Blood Type" width="100" />
        <el-table-column prop="height_cm" label="Height(cm)" width="110" />
        <el-table-column prop="education_level" label="Education" width="120" />
        <el-table-column prop="is_active" label="Status" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'info'">
              {{ row.is_active ? 'Active' : 'Inactive' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="registration_date" label="Registration Date" width="160">
          <template #default="{ row }">
            {{ formatDate(row.registration_date) }}
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="230">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row.donor_id)">
              View
            </el-button>
            <el-button type="primary" link @click="handleEdit(row)">
              Edit
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDelete(row)"
              :disabled="!row.can_delete"
              :title="!row.can_delete ? 'This donor has offspring records or vials used in orders and cannot be deleted' : ''"
            >
              Delete
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageChange"
        @current-change="handlePageChange"
        style="margin-top: 20px; justify-content: flex-end;"
      />
    </el-card>

    <!-- Add/Edit Dialog -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="Donor Code" prop="donor_code">
          <el-input 
            v-model="formData.donor_code" 
            placeholder="e.g., D001" 
            :disabled="isEdit"
          />
          <span v-if="isEdit" style="color: #909399; font-size: 12px;">
            Core fields cannot be modified: code, date of birth, blood type
          </span>
        </el-form-item>
        <el-form-item label="Full Name" prop="full_name">
          <el-input v-model="formData.full_name" />
        </el-form-item>
        <el-form-item label="Date of Birth" prop="date_of_birth">
          <el-date-picker
            v-model="formData.date_of_birth"
            type="date"
            placeholder="Select date"
            style="width: 100%"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="Blood Type" prop="blood_type">
          <el-select 
            v-model="formData.blood_type" 
            style="width: 100%"
            :disabled="isEdit"
          >
            <el-option label="A+" value="A+" />
            <el-option label="A-" value="A-" />
            <el-option label="B+" value="B+" />
            <el-option label="B-" value="B-" />
            <el-option label="AB+" value="AB+" />
            <el-option label="AB-" value="AB-" />
            <el-option label="O+" value="O+" />
            <el-option label="O-" value="O-" />
          </el-select>
        </el-form-item>
        <el-form-item label="Height (cm)" prop="height_cm" required>
          <div style="display: flex; align-items: center; gap: 8px;">
            <el-input-number v-model="formData.height_cm" />
            <span style="color: #909399; font-size: 13px; white-space: nowrap;">Range: 150-210</span>
          </div>
        </el-form-item>
        <el-form-item label="Weight (kg)" prop="weight_kg" required>
          <div style="display: flex; align-items: center; gap: 8px;">
            <el-input-number v-model="formData.weight_kg" :precision="1" />
            <span style="color: #909399; font-size: 13px; white-space: nowrap;">Range: 45-120</span>
          </div>
        </el-form-item>
        <el-form-item label="Education" prop="education_level" required>
          <el-select v-model="formData.education_level" placeholder="Please select" style="width: 100%">
            <el-option label="High School" value="High School" />
            <el-option label="Associate" value="Associate" />
            <el-option label="Bachelor" value="Bachelor" />
            <el-option label="Master" value="Master" />
            <el-option label="Doctorate" value="Doctorate" />
          </el-select>
        </el-form-item>
        <el-form-item label="Occupation" prop="occupation" required>
          <el-input v-model="formData.occupation" />
        </el-form-item>
        <el-form-item label="Contact Email" prop="contact_email" required>
          <el-input v-model="formData.contact_email" />
        </el-form-item>
        <el-form-item label="Contact Phone" prop="phone_number" required>
          <el-input v-model="formData.phone_number" placeholder="Enter phone number">
            <template #prepend>
              <el-select v-model="formData.country_code" placeholder="+86" style="width: 100px">
                <el-option label="+86 China" value="+86" />
                <el-option label="+1 USA" value="+1" />
                <el-option label="+44 UK" value="+44" />
                <el-option label="+81 Japan" value="+81" />
                <el-option label="+82 Korea" value="+82" />
                <el-option label="+65 Singapore" value="+65" />
                <el-option label="+852 Hong Kong" value="+852" />
                <el-option label="+853 Macau" value="+853" />
                <el-option label="+886 Taiwan" value="+886" />
              </el-select>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="Status" prop="is_active">
          <div style="display: flex; align-items: center; gap: 12px;">
            <el-switch v-model="formData.is_active" />
            <span :style="{ color: formData.is_active ? '#67C23A' : '#909399' }">
              {{ formData.is_active ? 'Active' : 'Inactive' }}
            </span>
          </div>
        </el-form-item>
        <el-form-item label="Medical Screening" v-if="!isEdit">
          <div style="display: flex; flex-direction: column; gap: 8px;">
            <div style="display: flex; align-items: center; gap: 12px;">
              <el-switch v-model="formData.create_screenings" />
              <span>Auto-create standard medical screening (all 7 tests passed)</span>
            </div>
            <span style="color: #909399; font-size: 12px;">
              When checked, automatically creates HIV, Hepatitis B, Hepatitis C, Syphilis, Genetic Screening, Chromosome Analysis, and Semen Analysis with all results passed/negative
            </span>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="handleSubmit">Confirm</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { donorAPI } from '@/api'

const router = useRouter()

// Search form
const searchForm = reactive({
  keyword: '',
  blood_type: '',
  is_active: ''  // Default: show all (active + inactive)
})

// Pagination
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// Data list
const donorList = ref([])
const loading = ref(false)

// Dialog
const dialogVisible = ref(false)
const dialogTitle = ref('Add Donor')
const isEdit = ref(false)  // Whether in edit mode (to disable core fields)
const formRef = ref(null)
const formData = reactive({
  donor_code: '',
  full_name: '',
  date_of_birth: '',
  blood_type: '',
  height_cm: null,
  weight_kg: null,
  education_level: '',
  occupation: '',
  contact_email: '',
  contact_phone: '',
  country_code: '+86',
  phone_number: '',
  is_active: true,
  create_screenings: true  // Default checked, auto-create medical screening
})

// Form validation rules
const formRules = {
  donor_code: [{ required: true, message: 'Please enter donor code', trigger: 'blur' }],
  full_name: [{ required: true, message: 'Please enter full name', trigger: 'blur' }],
  date_of_birth: [{ required: true, message: 'Please select date of birth', trigger: 'change' }],
  blood_type: [{ required: true, message: 'Please select blood type', trigger: 'change' }],
  height_cm: [
    { required: true, message: 'Please enter height', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('Please enter height'))
        } else if (value < 150) {
          callback(new Error('Height must be at least 150 cm'))
        } else if (value > 210) {
          callback(new Error('Height cannot exceed 210 cm'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  weight_kg: [
    { required: true, message: 'Please enter weight', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('Please enter weight'))
        } else if (value < 45) {
          callback(new Error('Weight must be at least 45 kg'))
        } else if (value > 120) {
          callback(new Error('Weight cannot exceed 120 kg'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  education_level: [{ required: true, message: 'Please select education level', trigger: 'change' }],
  occupation: [{ required: true, message: 'Please enter occupation', trigger: 'blur' }],
  contact_email: [
    { required: true, message: 'Please enter email', trigger: 'blur' },
    { type: 'email', message: 'Please enter valid email format', trigger: 'blur' }
  ],
  phone_number: [
    { required: true, message: 'Please enter phone number', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('Please enter phone number'))
        } else if (!/^\d+$/.test(value)) {
          callback(new Error('Phone number can only contain digits'))
        } else if (value.length < 7) {
          callback(new Error('Phone number must be at least 7 digits'))
        } else if (value.length > 15) {
          callback(new Error('Phone number cannot exceed 15 digits'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// Load list data
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const res = await donorAPI.getList(params)
    donorList.value = res.data || []
    pagination.total = res.count || 0
  } catch (error) {
    ElMessage.error('Failed to load data')
  } finally {
    loading.value = false
  }
}

// Search (reset to page 1)
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// Page change (do not reset page number)
const handlePageChange = () => {
  loadData()
}

// Reset
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    blood_type: '',
    is_active: ''  // After reset, show all
  })
  handleSearch()
}

// Add
const handleAdd = () => {
  dialogTitle.value = 'Add Donor'
  isEdit.value = false  // Add mode: core fields editable
  Object.assign(formData, {
    donor_id: null,
    donor_code: '',
    full_name: '',
    date_of_birth: '',
    blood_type: '',
    height_cm: null,
    weight_kg: null,
    education_level: '',
    occupation: '',
    contact_email: '',
    contact_phone: '',
    country_code: '+86',
    phone_number: '',
    is_active: true
  })
  dialogVisible.value = true
}

// Edit
const handleEdit = (row) => {
  dialogTitle.value = 'Edit Donor'
  isEdit.value = true  // Edit mode: core fields disabled
  Object.assign(formData, row)
  // Split phone number
  const { country_code, phone_number } = splitPhone(row.contact_phone)
  formData.country_code = country_code
  formData.phone_number = phone_number
  dialogVisible.value = true
}

// View details
const handleView = (id) => {
  router.push(`/donors/${id}`)
}

// Delete
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `Are you sure you want to delete donor ${row.full_name}?`,
      'Warning',
      {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }
    )
    await donorAPI.delete(row.donor_id)
    ElMessage.success('Deleted successfully')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('Failed to delete')
    }
  }
}

// Split phone number: extract country code and number from full phone
const splitPhone = (fullPhone) => {
  if (!fullPhone) return { country_code: '+86', phone_number: '' }
  
  // List of supported country codes (sorted by length from long to short to avoid matching errors)
  const countryCodes = ['+886', '+853', '+852', '+86', '+82', '+81', '+65', '+44', '+1']
  
  for (const code of countryCodes) {
    if (fullPhone.startsWith(code)) {
      return {
        country_code: code,
        phone_number: fullPhone.substring(code.length)
      }
    }
  }
  
  // If no known country code matched, default to +86
  return { country_code: '+86', phone_number: fullPhone.replace(/^\+/, '') }
}

// Merge phone number: country code + number
const mergePhone = () => {
  return formData.country_code + formData.phone_number.trim()
}

// Submit form
const handleSubmit = async () => {
  await formRef.value.validate()
  try {
    // Merge phone number
    const submitData = { ...formData }
    submitData.contact_phone = mergePhone()
    delete submitData.country_code
    delete submitData.phone_number
    
    if (formData.donor_id) {
      // Edit mode: exclude core fields (donor_code, date_of_birth, blood_type)
      const updateData = { ...submitData }
      delete updateData.donor_id
      delete updateData.donor_code      // Core field cannot be modified
      delete updateData.date_of_birth   // Core field cannot be modified
      delete updateData.blood_type      // Core field cannot be modified
      delete updateData.registration_date
      
      await donorAPI.update(formData.donor_id, updateData)
      ElMessage.success('Updated successfully')
    } else {
      // Add mode: send all fields
      await donorAPI.create(submitData)
      ElMessage.success('Created successfully')
    }
    dialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('Operation failed')
  }
}

// Format date
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('en-US')
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.donor-list {
  padding: 0;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

